<template>
  <div v-loading="loading" style="height: 100%">
    <van-nav-bar :right-text="postingDate" left-arrow left-text="返回" title="成品入库确认信息" @click-left="goBack"
                 @click-right="setPostDate"/>
    <van-calendar v-model="showCalendar" :max-date="maxDate" :min-date="minDate" @confirm="onConfirm"/>
    <van-cell-group :v-model="tableData" style="
          overflow: scroll;
          height: 520px;
          ::-webkit-scrollbar {
            display: none;
          }
        ">
      <van-row>
        <van-col span="14">
          <van-field v-model="tableData.materialno" label="物料编码" readonly/>
        </van-col>
        <van-col span="10">
          <van-field v-model="tableData.specification" label="规格" label-width="30%" readonly/>
        </van-col>
      </van-row>
      <van-field v-model="tableData.materialdes" label="物料描述" readonly/>
      <van-field v-model="tableData.batchno" label="批号" readonly/>
      <van-row>
          <van-field v-model="tableData.packinglotno" label="包装批" label-width="40%" readonly/>
      </van-row>
      <van-field v-model="tableData.kdmat" label="客户物料" readonly/>
      <!--            <van-field v-model="tableData.predictlocation" label="预收库位" readonly />-->
      <van-row>
        <van-col span="12">
          <van-field v-model="tableData.confirmed" label="已确认数量" readonly/>
        </van-col>
        <van-col span="12">
          <van-field v-model="tableData.notconfirm" label="未确认数量" readonly/>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="12">
          <van-field v-model="tableData.totalquantity" label="确认总数量"/>
        </van-col>
        <van-col span="12">
          <van-field v-model="tableData.batchquantity" label="预收数量" readonly/>
        </van-col>
      </van-row>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocompletePart" v-model="tableData.predictlocation" :fetch-suggestions="storageLocationSearchPart"
                           :rules="{
                      required: true,
                      message: '请选择库位',
                      trigger: 'blur',
                    }" label="预收库位" placeholder="预收库位" style="width: 100%;" value-key="codeanddes"
                           @select="handleSelect"></el-autocomplete>
        </van-col>
      </van-row>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocomplete" v-model="tableData.actuallocation" :fetch-suggestions="storageLocationSearch"
                           :rules="{
                      required: true,
                      message: '请选择库位',
                      trigger: 'blur',
                    }" label="实收库位" placeholder="实收库位" style="width: 100%;"
                           value-key="codeanddes"></el-autocomplete>
        </van-col>
      </van-row>
      <van-field v-if="dc_flag == 'X'" ref="code_input" v-model="code_input"
                 left-icon="scan" placeholder="请扫描吨槽码" style="border: solid 1px #3793fb; border-radius: 5px" @input="onScanBarrelCode"/>
      <van-swipe ref="swiper" style="border: solid #3793fb 1px;border-top:none" width="100%" @change="onChange">
        <van-swipe-item v-for="(domain, domainIndex) in tableData.bucket" :key="domainIndex">
          <van-field v-model="domain.numberOfBarrels" label="吨槽号" readonly></van-field>
          <van-field v-model="domain.quantity" label="数量" @input="quantityChange"></van-field>
          <van-button v-if="current >= 0" class="custom-swipe-delete" color="linear-gradient(to right, #ff6034, #ee0a24)"
                      @click="onDeleteBarrel(domainIndex)">
            删除
          </van-button>
        </van-swipe-item>
        <template #indicator>
          <div v-if="current >= 0" class="custom-indicator">{{ current + 1 }}/{{ totalSize }}</div>
        </template>
      </van-swipe>
    </van-cell-group>
    <van-button block style="
          position: fixed;
          bottom: 0px;
          border: #3793fb solid 1px;
          border-radius: 2px;
          background-color: #3793fb;
          line-height: var(--footer-height);
        " type="primary" @click="dialogVisible = true">成品入库过账
    </van-button>
    <el-dialog
        :visible.sync="dialogVisible"
        title="是否过账"
        width="70%">
      <span>确定成品入库过账?</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="onSubmit">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      tableData: {
        materialNo: "",
        batchNo: "",
        materialDes: "",
        customerLotNo: "",
        specification: "",
        totalquantity: "",
        bucket: [],

      },
      storageLocationList: [],
      storageLocationListPart: [],
      loading: false,
      index: 0,
      totalSize: 0,
      current: -1,
      code_input: '',
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      minDate: this.getMonthBeforeDate(),
      maxDate: this.getMonthAfterDate(),
      dc_flag: false
    };
  },
  mounted() {
    //成品入库信息
    this.getProductInboundInfo(this.$route.query.codeInfo);
    //获取库位List
    this.getStorageLocationList();
  },
  methods: {
    handleSelect(item) {
      this.tableData.batchquantity = item.batchquantity;
      this.tableData.confirmed = item.confirmed;
      this.tableData.notconfirm = item.notconfirm;
    },
    getNowFormatDate(date) {
      let
          year = date.getFullYear(), //获取完整的年份(4位)
          month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
          strDate = date.getDate() // 获取当前日(1-31)
      if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
      return `${year}-${month}-${strDate}`
    },
    setPostDate() {
      this.showCalendar = true;
    },
    onConfirm(date) {
      this.showCalendar = false;
      this.$dialog.confirm({
        title: '过账日期',
        message: '此选择将更改ERP过账日期',
      })
          .then(() => {
            this.postingDate = this.getNowFormatDate(date);
          })
          .catch(() => {
          });
    },
    async getProductInboundInfo(codeInfo) {
      let scanInfo = {
        code: codeInfo + ',' + localStorage.getItem("plant")
      };
      const {data: res} = await this.$http.post(
          "/ProductionVerifyMateriel",
          scanInfo
      );
      this.tableData = res[0];
      this.dc_flag = res[0].zifdc;
      this.storageLocationListPart = res[0].location;
      this.tableData.actuallocation = res[0].predictlocation;
      console.log("res[0]", res[0]);
    },
    async getStorageLocationList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const {data: res} = await this.$http.post(
          "/StorageLocationList",
          scanInfo
      );
      this.storageLocationList = res;
    },
    //返回
    goBack() {
      this.$router.push({
        path: "/ScanView",
        query: {title: '成品标签扫描', key: 4},
      });
    },
    onScanBarrelCode(event) {
      this.getBucket(event);
    },
    async getBucket(bucketNo) {
      let scanInfo = {
        code: bucketNo,
        productionNo: this.tableData.productionno,
      };
      console.log("scanInfo", scanInfo);
      const {data: res} = await this.$http.post(
          "/ProductionVerifyBucket",
          scanInfo
      );
      console.log("res", res);
      if(res[0].type  && res[0].type === 'E'){
        this.$toast.fail(res[0].message);
        this.code_input = '';
        return
      }
      if (res.length && res[0].bucketnumber) {
        var requestData = this.tableData;
        for (var i in requestData.bucket) {
          if (requestData.bucket[i].numberOfBarrels === res[0].bucketnumber) {
            this.$message({
              message: "扫描失败，请勿重复扫描同一桶号",
              type: "error",
            });
            this.code_input = '';
            return
          }
        }
        var specification = this.tableData.specification;
        this.tableData.bucket.push({numberOfBarrels: res[0].bucketnumber, quantity: specification});
        this.tableData.noofbarrels = parseInt(this.tableData.noofbarrels) + 1;
        this.tableData.totalquantity = parseInt(this.tableData.totalquantity) + parseInt(specification);
        this.totalSize = this.tableData.bucket.length;
        this.current = this.totalSize - 1;
        this.$refs.swiper.swipeTo(this.current);
        this.code_input = '';
      } else {
        this.code_input = '';
        this.$toast.fail('条码信息错误');
      }
    },
    onChange(index) {
      this.current = index;
    },
    onDeleteBarrel(domainIndex) {
      this.tableData.totalquantity -= this.tableData.bucket[domainIndex].quantity;
      this.tableData.bucket.splice(domainIndex, 1);
      this.tableData.noofbarrels -= 1;
      this.totalSize = this.tableData.bucket.length;
      if (this.current > this.totalSize - 1) {
        this.current = this.totalSize - 1;
      }
      this.$refs.swiper.swipeTo(this.current);
    },
    //入库过账
    onSubmit() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.postRawMaterialInbound();
      }, 1000);
      this.dialogVisible = false;
    },
    handlePageChange(currentPage) {
      this.index = currentPage - 1;
    },
    //新增库位信息
    addDomain() {
      if (this.tableData.bucket === undefined) {
        this.tableData.bucket = [];
      }
      this.tableData.bucket.push({
        location: "",
        locationdes: "",
        noofbarrels: "",
        quantity: "",
        codeanddes: "",
      });
    },
    //删除库位信息
    removeDomain(item) {
      var index = this.tableData.bucket.indexOf(item);
      if (index !== -1) {
        this.tableData.bucket.splice(index, 1);
      }
      this.locationChange();
    },
    //库位搜索帮助
    storageLocationSearchPart(queryString, cb) {
      var storageLocationList = this.storageLocationListPart;
      var results = queryString
          ? storageLocationList.filter(this.createFilter(queryString))
          : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //库位搜索帮助
    storageLocationSearch(queryString, cb) {
      var storageLocationList = this.storageLocationList;
      var results = queryString
          ? storageLocationList.filter(this.createFilter(queryString))
          : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.codeanddes
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //选择库位桶数自动计算总数量
    storageLocationHandleSelect() {
      this.locationChange();
    },
    //自动计算总数量
    locationChange() {
      var locationList = this.tableData.bucket;
      var totalQuantity = 0;
      var specification = this.tableData.specification;
      if (specification == '') {
        specification = 1;
      }

      for (var i in locationList) {
        if (
            locationList[i].codeanddes != "" &&
            locationList[i].noofbarrels != ""
        ) {
          locationList[i].quantity =
              locationList[i].noofbarrels * specification;
          totalQuantity = totalQuantity + parseInt(locationList[i].noofbarrels);
        }
      }

      this.tableData.totalquantity =
          totalQuantity * specification;
    },
    quantityChange() {
      var total = 0;
      for (var i in this.tableData.bucket) {
        if (this.tableData.bucket[i].quantity !== '') {
          total += parseInt(this.tableData.bucket[i].quantity);
        }
        this.tableData.totalquantity = total;
      }
    },
    noOfBarrelsChange() {
      if (this.tableData.bucket && this.tableData.specification !== '') {
        this.tableData.totalquantity = this.tableData.specification * this.tableData.noofbarrels;
      }
    },
    //过账接口
    async postRawMaterialInbound() {
      var requestData = this.tableData;
      var specification = this.tableData.specification;
      if (specification == '') {
        specification = 1;
      }
      var bucket = [];
      for (var i in requestData.bucket) {
        bucket.push({
          numberOfBarrels: requestData.bucket[i].numberOfBarrels,
          quantity:
          requestData.bucket[i].quantity,
        });
      }
      let inputInfo = {
        materialNo: requestData.materialno,
        plant: localStorage.getItem("plant"),
        userName: localStorage.getItem("erpId"),
        batchNo: requestData.batchno,
        materialDes: requestData.materialdes,
        packingLotNo: requestData.packinglotno,
        productionLotNo: requestData.productionlotno,
        kdmat: requestData.kdmat,
        productionNo: requestData.productionno,
        batchQuantity: requestData.batchquantity,
        confirmed: requestData.confirmed,
        postDate: this.postingDate,
        predictLocation: requestData.predictlocation.split("|")[0],
        notConfirm: requestData.notconfirm,
        actualLocation: requestData.actuallocation.split("|")[0],
        totalQuantity: requestData.totalquantity,
        zifdc: this.dc_flag,
        specification: requestData.specification,
        bucket: bucket,
      };
      console.log("inputInfo", inputInfo)
      const {data: res} = await this.$http.post(
          "/PostProductionVerify",
          inputInfo
      );
      var response = res[0];
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "入库失败，请联系系统维护人员",
          type: "error",
        });
      }
    },
  },
}
</script>

<style>
.el-input__inner {
  border: 0px;
  outline: none;
}
</style>